package com.ll.sender;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.ll.config.EmailServerConfiguration;
import com.ll.service.EmailMessageService;
import com.ll.vo.response.EmailMessageResponseVo;
/**
 * 
 * @author dwliu
 *
 * @date 2016年4月19日
 */
@Service
public class TaskQueue implements ApplicationContextAware {

	private static Logger LOGGER = LoggerFactory.getLogger(TaskQueue.class);

	private static int taskQueueSize;

	private static EmailServerConfiguration emailServerConfiguration = new EmailServerConfiguration();

	private static ApplicationContext applicationContext;

	static {
		taskQueueSize = emailServerConfiguration.getTaskQueueSize("taskQueueSize");
	}

	private static BlockingQueue<EmailSenderTask> taskQueue = new LinkedBlockingQueue<EmailSenderTask>(taskQueueSize);

	public static void addQueue(EmailMessageResponseVo emailMessageResponseVo) {
		try {
			taskQueue.put(new EmailSenderTask(emailMessageResponseVo));
		} catch (InterruptedException e) {
			// TODO 处理任务队列打断
			LOGGER.error("addQueue",e);
			EmailMessageService emailMessageService = applicationContext.getBean(EmailMessageService.class);
			emailMessageService.unlockEmailMessage(emailMessageResponseVo.getId());
		}
	}

	// 取出location对应队列首位对象
	public static EmailSenderTask takeData() {
		EmailSenderTask emailSenderTask = null;
		try {
			emailSenderTask = taskQueue.take();
		} catch (InterruptedException e) {
			LOGGER.info("对应队列取出数据失败！",e);
		}
		return emailSenderTask;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		TaskQueue.applicationContext = applicationContext;
	}

}
